//
//  LoginViewController.m
//  FinancialProduct
//
//  Created by Stella on 2017/8/24.
//  Copyright © 2017年 maq. All rights reserved.
//
#import "CKPuslichTool.h"
#import "ValidateTools.h"
#import "SVProgressHUD.h"
#import "HandleNetLogin.h"
#import "LoginViewController.h"
#import "UserModel.h"
#import "RegisterViewController.h"
#import "AppDelegate.h"
#import "MyNavigationController.h"
#import "PicPassController.h"
#import "CaptchaView.h"
#import "DBAcquireAuthCodeButton.h" 
@interface LoginViewController (){
    NSString * sendPhoneNo;
    BOOL isApprove;
}
@property (weak, nonatomic) IBOutlet UILabel *reminder;
@property (weak, nonatomic) IBOutlet UILabel *reminder1;
@property (weak, nonatomic) IBOutlet UILabel *reminder2;
@property (weak, nonatomic) IBOutlet UILabel *reminder3;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *passTextField;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet DBAcquireAuthCodeButton *codeButton;
@property (weak, nonatomic) IBOutlet CaptchaView *codePic;
@property (strong,nonatomic)NSDate *oldDate;
@property (strong,nonatomic)NSString *mCode;
@property (weak, nonatomic) IBOutlet UILabel *companyName;


@end

@implementation LoginViewController

-(void)MoveTextfileContent:(UITextField *)textfile{
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 10, 27)];
 
    imageView.contentMode = UIViewContentModeCenter;
    textfile.leftView = imageView;
    textfile.leftViewMode = UITextFieldViewModeAlways;
    textfile.layer.cornerRadius = 5;
}


- (IBAction)goRegisterController:(id)sender {
    
    RegisterViewController *vcc=(RegisterViewController *)[CKPuslichTool getViewControllerFromStroyBoard:@"Login" viewID:@"RegisterViewController"];
//    vcc.isApprove = isApprove;
    [self.navigationController pushViewController:vcc animated:YES];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    isApprove = YES;
    [HandleNetLogin getCompanyNameSuccess:^(NSDictionary *data) {
        if ([data[@"Company"] length]==0) {
            self.companyName.text=@"";
        }else{
            self.companyName.text=@"陆浦集团旗下私人财富管理平台";
        }
//        if (![data[@"IsApprove"] isEqualToString:@"是"]) {
//            isApprove = NO;
//        }
//
    } Failure:^(NSString *errorInfo) {
        self.companyName.text=@"";
    }];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    self.codeTextField.hidden=YES;
    self.codeButton.hidden=YES;
  
    sendPhoneNo=@"";
    _mCode=@"";
    self.reminder1.text=@"";
    self.reminder2.text=@"";
    self.reminder3.text=@"";
    self.reminder.text=@"";
    [self.phoneTextField       addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.codeTextField       addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    [self.phoneTextField addTarget:self action:@selector(textFieldDidEndEditing:) forControlEvents:UIControlEventEditingDidEnd];
    [self setTextfile:self.phoneTextField img:[UIImage imageNamed:@"iPhone-3(G)"]];
    [self setTextfile:self.passTextField img:[UIImage imageNamed:@"mima"]];
    [self MoveTextfileContent:self.codeTextField];
    self.loginButton.layer.cornerRadius=5;
    self.codeButton.layer.cornerRadius=5;
    self.codeTextField.layer.cornerRadius=5;
    
//    self.phoneTextField.text = @"18049837585";//@"13891449657";//;
//    self.passTextField.text = @"11111111";
}


- (IBAction)login:(id)sender {
//    PicPassController *vcc=(PicPassController *)[CKPuslichTool getViewControllerFromStroyBoard:@"Login" viewID:@"PicPassController"];
//    [self.navigationController pushViewController:vcc animated:YES];
//    return;
    
    self.reminder1.text=@"";
    self.reminder2.text=@"";
    self.reminder3.text=@"";
    self.reminder.text=@"";
    if ( self.phoneTextField.text.length == 0) {
        self.reminder1.text=@"*请输入手机号";
        return;
    }
    if (![ValidateTools validateMobile:self.phoneTextField.text]) {//self.phoneTextField.text.length != 11
        self.reminder1.text=@"*手机号码格式不正确";
        return;
    }
    if (self.passTextField.text.length == 0) {
        
        self.reminder2.text=@"*请输入密码";
        return;
    }
    
    if ([self.phoneTextField.text isEqualToString:@"18229027840"]) {

    }else{
        if (self.codeTextField.text.length == 0) {
            
            self.reminder3.text=@"*请输入验证码";
            return;
        }
        if (![self.codeTextField.text isEqualToString:_mCode]) {
            self.reminder3.text=@"*验证码验证失败";
            return;
        }
        
        NSDate *currentDate=[NSDate date];
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        
        NSInteger interval = [zone secondsFromGMTForDate:currentDate];
        
        NSDate *localDate1 = [currentDate dateByAddingTimeInterval:interval];
        NSDate *localDate2 = [_oldDate dateByAddingTimeInterval:interval];
        
        //计算时间差间隔
        NSTimeInterval timeBetween = [localDate1 timeIntervalSinceDate:localDate2];
        NSLog(@"timeBetween---%f",timeBetween);
        if (timeBetween>60*10) {
            
            self.reminder3.text=@"*验证码已失效";
            return;
        }
        //获取验证码手机与当前手机号是否一致
        NSString *CodePhone=self.phoneTextField.text;
        
        if (![CodePhone isEqualToString:sendPhoneNo]) {
            
            self.reminder3.text=@"*获取验证码";
            return;
        }
        
    }
    //调用接口
    /**
     调用LoginCheck，返回信息为“账号或密码错误”；返回信息为“正式客户”，跳转“我的账户”；返回信息为“临时客户”，跳转“首页”
     ***/
    [HandleNetLogin CheckLoginForPhone:self.phoneTextField.text Password:self.passTextField.text isShow:YES Success:^(NSDictionary *data) {
        /***
         data =     (
         {
         Accountstatus = 2;//1 正式客户  2 临时客户
         CustomerID = 0;
         Result = 1;
         StatusLogo = 0;
         }
         );
         msg = "请求成功";
         state = true;
         ***/
        [[NSUserDefaults standardUserDefaults] setObject:self.passTextField.text forKey:@"PASSCODE"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        NSMutableDictionary *infoData=[[NSMutableDictionary alloc] initWithDictionary:data];
        [infoData setObject:self.phoneTextField.text forKey:@"phone"];
        UserModel *model = [UserModel userInfo:infoData];
        [model save];
        
        [UserModel setUserLogin:YES];
        
        
        BOOL haspic=NO;
        for (UIViewController *vc in self.navigationController.viewControllers) {
            if ([vc isKindOfClass:[PicPassController class]]) {
                haspic=YES;
                [self.navigationController popToViewController:vc animated:NO];
                break;
            }
        }
        if (!haspic) {
            PicPassController *vcc=(PicPassController *)[CKPuslichTool getViewControllerFromStroyBoard:@"Login" viewID:@"PicPassController"];
            [self.navigationController pushViewController:vcc animated:YES];
        }
        
        //        AppDelegate *tempAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        //        PicPassController *pic=(PicPassController *)[CKPuslichTool getViewControllerFromStroyBoard:@"Login" viewID:@"PicPassController"];
        //        MyNavigationController *nav = [[MyNavigationController alloc]initWithRootViewController:pic];
        //        tempAppDelegate.window.rootViewController =nav;
    } Failure:^(NSString *errorInfo) {
        self.reminder.text=[NSString stringWithFormat:@"*%@",errorInfo];
        if ([errorInfo rangeOfString:@"登录名或密码错误"].length > 0) {
            self.passTextField.text = @"";
        }
    }];
    
    
}

- (IBAction)back:(id)sender {
//    self.tabBarController.selectedIndex = self.tabIndex-1;
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

-(IBAction)tarStartButtonTimers:(id)sender{
    
    
    self.reminder1.text=@"";
    self.reminder2.text=@"";
    self.reminder3.text=@"";
    self.reminder.text=@"";
    if ( self.phoneTextField.text.length == 0) {
        self.reminder1.text=@"*请输入手机号";
        return;
    }
    if ( ![ValidateTools validateMobile:self.phoneTextField.text]) {
        self.reminder1.text=@"*手机号码格式不正确";
        return;
    }
    if (self.passTextField.text.length == 0) {
        
        self.reminder2.text=@"*请输入密码";
        return;
    }
    
    [HandleNetLogin CheckLoginForPhone:self.phoneTextField.text Password:self.passTextField.text isShow:NO Success:^(NSDictionary *data) {
        /***
         data =     (
         {
         Accountstatus = 2;//1 正式客户  2 临时客户
         CustomerID = 0;
         Result = 1;
         StatusLogo = 0;
         }
         );
         msg = "请求成功";
         state = true;
         ***/
        [HandleNetLogin getCodeForPhone:self.phoneTextField.text Success:^(NSDictionary *data) {
            
            _mCode = data[@"Verificationcode"];;
            sendPhoneNo=self.phoneTextField.text;
            _oldDate=[NSDate date];
            [_codeButton tarStartButtonTimer];
        } Failure:^(NSString *errorInfo) {
            self.reminder.text=[NSString stringWithFormat:@"*%@",errorInfo];
        }];
        

     
        
    } Failure:^(NSString *errorInfo) {
        self.reminder.text=[NSString stringWithFormat:@"*%@",errorInfo];
        if ([errorInfo rangeOfString:@"登录名或密码错误"].length > 0) {
            self.passTextField.text = @"";
        }
    }];
     
}
-(void)textFieldDidEndEditing:(UITextField *)mTextField{
    NSString *text=mTextField.text;
    if (text.length==11) {
        if ([text isEqualToString:@"18229027840"]) {
            return;
        }
        self.codeTextField.hidden=NO;
        self.codeButton.hidden=NO;
       
    }
    
}

- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField==_phoneTextField) {
        if (textField.text.length>11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }else if(textField==_codeTextField){
        if (textField.text.length>20) {
            textField.text = [textField.text substringToIndex:20];
        }
    }
    

}

-(void)setTextfile:(UITextField *)textfile img:(UIImage *)img{
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50, 27)];
    imageView.image =img;
    imageView.contentMode = UIViewContentModeCenter;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(imageView.frame.size.width-5, 6, 1, textfile.frame.size.height-6*2)];
    view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [textfile addSubview:view];
    
    textfile.leftView = imageView;
    textfile.leftViewMode = UITextFieldViewModeAlways;
    textfile.layer.cornerRadius = 5;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
